<?php
namespace app\staff\controller;

use think\Request;
use think\Db;
use think\Session;
use think\Controller;
use think\Config;
use Godok\Org\Auth;
use think\Log;

class Freqlist extends Controller
{

	// 常用清单列表
	function freqList(){
		$param = Request()->param();
		//分类
		$cate = Db::table('sdzx_user_freqlist')->alias('ur')
		->field('g.category_id_1,gc.cate_name,ur.user_id')
		->join('sdzx_goods g','g.goods_id=ur.goods_id')
		->join('sdzx_goods_category gc','gc.cate_id=g.category_id_1')
		->where('ur.user_id',$param['user_id'])
		->group('g.category_id_1')
		->select();

		//各个类下面的商品
		$list = Db::table('sdzx_user_freqlist')->alias('ur')
		->field('g.goods_id,g.goods_name,g.picture,g.unit,g.category_id_1')
		->join('sdzx_goods g','g.goods_id=ur.goods_id')
		->join('sdzx_goods_category gc','gc.cate_id=g.category_id_1')
		->where('ur.user_id',$param['user_id'])
		->select();

		foreach ($list as $key => $value) {
			$list[$key]['specval'] = Db::name('goods_specval')
			->field('specval_name,specval_id,price,unit,unit_price,spec_name')
			->where('goods_id',$value['goods_id'])
			->select();

			//规格价--最小
			$min = Db::table('sdzx_goods_specval')
			->where('goods_id',$value['goods_id'])
			->min('price');

			//规格价--最大
			$max = Db::table('sdzx_goods_specval')
			->where('goods_id',$value['goods_id'])
			->max('price');

			if(count($list[$key]['specval'])==1){
				$list[$key]['unit'] = $list[$key]['specval'][0]['unit'];
				$list[$key]['region'] = $list[$key]['specval'][0]['price'];
			}else{
				$list[$key]['unit'] = $value['unit'];
				$list[$key]['region'] = $min.'-'.$max;
			}
		}

		foreach ($cate as $key => $value) {
			foreach ($list as $k => $val) {
				if($value['category_id_1']==$val['category_id_1']){
					$cate[$key]['list'][] = $list[$k];
				}
			}
		}
		$this->success('success','',$cate);
	}

	//加入清单
	function addFreq(){
		$param = Request()->param();
		$res = Db::name('user_freqlist')->where(['user_id'=>$param['user_id'],'goods_id'=>$param['goods_id']])->find();
		if($res){
			$this->error('商品已在常用清单中，请勿重复添加');
		}else{
			$data = [
				'user_id'  => $param['user_id'],
				'goods_id' => $param['goods_id'],
				'add_time' => date('Y-m-d H:i:s')
			];
			$res = Db::name('user_freqlist')->insert($data);
			if ($res) {
				$this->success('加入成功');
			}else{
				$this->error('加入失败');
			}
		}
	}

	//删除清单
	function delFreq(){
		$param = Request()->param();
		$map = [
			'user_id'  => $param['user_id'],
			'goods_id' => $param['goods_id']
		];
		$res = Db::name('user_freqlist')->where($map)->delete();
		if ($res) {
			$this->success('删除成功');
		}else{
			$this->error('删除失败');
		}
	}

}


